package com.chengqj.userserverprovider.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("uid", 11111);
        map.put("exp", new Date(System.currentTimeMillis() + 30 * 60 * 1000));
        String jwt = generatorToken(map);
        System.out.println(jwt);
        Claims chaim = phaseToken(jwt);
        System.out.println(chaim.get("uid"));
    }

    private static Key generatorKey() {
        //        System.out.println(UUID.randomUUID().
//                toString().replace("-",""));
        SignatureAlgorithm saa = SignatureAlgorithm.HS256;
        byte[] bin = DatatypeConverter.parseBase64Binary
                ("f3973b64918e4324ad85acea1b6cbec5");
        Key key = new SecretKeySpec(bin, saa.getJcaName());
        return key;
    }

    public static String generatorToken(Map<String, Object> payLoad) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return Jwts.builder().setPayload(objectMapper.writeValueAsString(payLoad))
                    .signWith(SignatureAlgorithm.HS256, generatorKey()).compact();
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(),e);
            e.printStackTrace();
        }
        return null;
    }


    public static Claims phaseToken(String token) {
        try {
            Jws<Claims> claimsJwt = Jwts.parser().setSigningKey(generatorKey()).parseClaimsJws(token);
            return claimsJwt.getBody();
        } catch (SignatureException e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

}
